# -*- coding: utf-8 -*-  

import tornado.httpserver
import tornado.ioloop
import tornado.web
import tornado.escape
import os
import time
#module to get contents
import readContent
import suggest
import jieba


class MainHandler( tornado.web.RequestHandler ):
	def get( self ):
		self.render( "search.html" )

class ListResultHandler( tornado.web.RequestHandler ):
	def get( self ):
		#the answers of jieba are encoded in unicode
		#and jieba can automatically realize what the encoding method of its inputs
		searchName = self.get_argument( "searchName" )
		cutList = jieba.cut( searchName )
		
		#create a list store the number of food that meet the searchName(allow repeat)
		subNameList = []
		for subItem in cutList:
			if cutNameResult.has_key( subItem.encode("utf-8") ):
				for number in cutNameResult[subItem.encode("utf-8")]:
					subNameList.append( int(number) )
		
		subNameList.sort()
		
		if len( subNameList ) == 0:
			tips = "Oops!"
			feedback = "sorry, 我们找不到你要的东西，可以尝试其他关键字~"
			toShowList = []
		else:
			tips = "Aha!"
			feedback = "你要的结果~"
			
			#make sure no repeat, instead we mark down their exist times and sort again
			subNameListNoRepeat = []
			subNameListNoRepeat.append( [subNameList[0], 1] )
			iter = 1
			while iter < len( subNameList ):
				if subNameList[iter] == subNameListNoRepeat[-1][0]:
					subNameListNoRepeat[-1][1] += 1
				else:
					subNameListNoRepeat.append( [subNameList[iter], 1] )
				
				iter += 1
				
			subNameListNoRepeat.sort(cmp = lambda x,y:cmp(y[1],x[1]))
			
			#try to get the most related foods
			if len( subNameListNoRepeat ) > 5:
				subNameListNoRepeat = subNameListNoRepeat[:5]
			
			#get the related foods' name
			toShowList = []
			for food in foods:
				for subName in subNameListNoRepeat:		
					if subName[0] == int(foods[food]["number"]):
						toShowList.append( food )
		
		
		self.render( "listResult.html", tips = "Oops!", toShowList = toShowList, feedback = feedback )
		
class TopicHandler( tornado.web.RequestHandler ):
	def get( self ):
		#get the food name
		foodName = self.get_argument( "foodName" ).encode("utf-8")

		#get the tags
		tagString = ''
		for foodTag in foods[foodName]["tags"]:
			tagString = tagString + foodTag +"|"
			
		tagString = foodName + " : " + tagString
		
		#get the introdutions
		introList = []
		if foods[foodName].has_key( "intros" ):
			for introsItem in foods[foodName]["intros"]:
				introList.append( introsItem + ":" + foods[foodName]["intros"][introsItem] )
		
		#get the image path
		picPath = os.path.join( foods[foodName]["number"], "pic.jpg" )
		staticPath = os.path.join( os.path.dirname( __file__ ), "static" )
		if not os.path.isfile( os.path.join( staticPath, picPath ) ):
			picPath = ""
		
		#get the suggestion
		queue = suggest.suggest( foods[foodName], foods, 5 )
		sugguestionList = []
		
		i = 0
		while i < 5:
			node = queue.pop()
			print node["priorityNum"]
			sugguestionList.append( node["name"] )
			i += 1
		
		#get the link of the topic
		link = foods[foodName]["link"]
		
		self.render( "topic.html", foodName = foodName, tags = tagString, introList = introList, sugguestionList = sugguestionList,
					topicLink = link, picPath = picPath )

					
jieba.initialize()
					
#get a dictionary represent the result of cutting all the names
cutNameResult = readContent.readCutNameResult()

#return a dictionary represent all the food topics and their contents
foods = readContent.readContent()

test = open( os.path.join( os.path.dirname(__file__), "log" ), "w" )
for item in foods:
	test.write( item )
	test.write( ":" )
	test.write( str(foods[item]["vector"]) + "\n" )
	

print "ready to run"

	
app = tornado.web.Application (
	[( r"/", MainHandler ),
	( r"/listResult", ListResultHandler ),
	( r"/topic", TopicHandler )],
	debug = True,
	static_path = os.path.join( os.path.dirname( __file__ ), "static" ),
	template_path = os.path.join( os.path.dirname( __file__ ), "template" ),
	autoscape = None
)

if __name__ == "__main__":
	http_server = tornado.httpserver.HTTPServer(app)
	http_server.listen(8888, '172.18.156.93')
	tornado.ioloop.IOLoop.instance().start()